package com.woniu.util;

import com.woniu.entity.TbUser;
import com.woniu.mapper.TbUserMapper;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class MinIOUtil {
    @Resource
    private MinioClient minioClient;
    @Resource
    private TbUserMapper userMapper;

    public Map<String,Object> upload(MultipartFile file, String bucketName) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //文件是否存在
        if (file.isEmpty()){
            map.put("code",400);
            map.put("msg","文件不存在");
            return map;
        }
        //桶是否存在
        boolean flag = minioClient.bucketExists(bucketName);
        if (!flag) {
            //创建桶
            minioClient.makeBucket(bucketName);
        }
        //在桶内创建文件夹区分文件 避免重名 目录/文件名.后缀
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //重写文件名
        String replace = UUID.randomUUID().toString().replace("-", "");
        String newFileName = replace + suffix;

        //创建目录
        LocalDate now = LocalDate.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        String format = now.format(dtf);

        //上传文件
        InputStream inputStream = file.getInputStream();
        //获取文件大小
        PutObjectOptions options = new PutObjectOptions(inputStream.available(),-1);
        minioClient.putObject(bucketName,format + "/" + newFileName,
                inputStream,options);
        log.info("文件上传成功");
        map.put("code",200);
        map.put("msg","文件上传成功");


        String objectUrl = minioClient.getObjectUrl(bucketName, format + "/" + newFileName);
        map.put("url",objectUrl);
        TbUser tbUser = userMapper.selectByPrimaryKey(1L);
//        tbUser.setImgurl(objectUrl);
        int i = objectUrl.indexOf("9000")+4;
        String imgUrl = objectUrl.substring(i);
        tbUser.setImgurl(imgUrl);
        int i1 = userMapper.updateByPrimaryKeySelective(tbUser);
        map.put("imgUrl",imgUrl);
        return map;
    }
}
